
package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.api.R;
import com.itheima.common.*;
import com.itheima.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: lcc
 * @Desc: Web容器Servlet过滤器
 * @Date: 2022-06-05 10:39:37
 */

@WebFilter
@Slf4j
public class LoginCheckFilter implements Filter {
    @Autowired
    private RedisTemplate redisTemplate;

/**
     * 支持通配符的路径匹配对象
     */

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

/**
     * 请求放行的路径
     */

    private static final String[] passUrls = {
            "/employee/login",
            "/backend/page/login/login.html",
            "/backend/api/**",
            "/backend/images/**",
            "/backend/plugins/**",
            "/backend/styles/**",
            "/backend/js/**",
            "/backend/favicon.ico"
            //TODO
    };
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("LoginCheckFilter当前线程的ID为：-------"+Thread.currentThread().getId()+"-----------");
        //1）拦截到请求，获取到请求路径
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();

        log.info("请求路径为：{}",requestURI);
        //2）判断请求路径属于哪一类
        boolean check = check(requestURI);
        //不登录可以访问的资源
        //3）不登录可以访问的资源，直接放行
        if(check){
            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request,response);//放行操作
            return;//方法不再继续执行
        }
        //登录才可以访问
        String empId = null;
        String userId = null;
        Cookie[] cookies = request.getCookies();
        if(cookies == null){
            log.info("用户未登录");
            //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
            response.sendRedirect("/backend/page/login/login.html");
            //response.setContentType("text/html;charset=UTF-8");
            //response.getWriter().write(JSON.toJSONString(new Result(Code.UNAUTHORIZED, MessageConstant.NOT_LOGIN)));
            return;
        }
        for (Cookie cookie : cookies) {
            String token = (String)cookie.getName();
            //判断是否有员工登录
            if(EmployeeConstant.TOKEN.equals(token)){
                empId = cookie.getValue();
            }
            //判断是否有用户登录
            if(EmployeeConstant.USER_TOKEN.equals(token)){
                userId = cookie.getValue();
            }
        }
        //4.1) 如果用户没有登录，返回友好错误提示信息
        if(empId == null && userId == null){
            log.info("用户未登录");
            //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
            response.sendRedirect("/backend/page/login/login.html");
            //response.setContentType("text/html;charset=UTF-8");
            //response.getWriter().write(JSON.toJSONString(new Result(Code.UNAUTHORIZED, MessageConstant.NOT_LOGIN)));
            return;
        }
        Object empID = request.getSession().getAttribute(empId);
        Object userID = request.getSession().getAttribute(userId);
        if(empID == null && userID == null){
            log.info("用户未登录");
            response.sendRedirect("/backend/page/login/login.html");
            //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
            //response.setContentType("text/html;charset=UTF-8");
            //response.getWriter().write(JSON.toJSONString(new Result(Code.UNAUTHORIZED, MessageConstant.NOT_LOGIN)));
            return;
        }
        //--------把用户数据存入当前线程---------------
        if(empID != null){
            Long eId = (Long)empID;
            BaseContext.setCurrentId(eId);
        }
        if(userID != null){
            Long uId = (Long)userID;
            BaseContext.setUserId(uId);
        }
        System.out.println("员工ID:"+BaseContext.getCurrentId());
        System.out.println("用户手机号:"+BaseContext.getUserId());
        //4）登录才可以访问的资源
        //4.2) 如果用户已经登录，放行
        log.info("用户已登录，{}，请求放行"+request);
        filterChain.doFilter(request,response);//放行操作
        return;//方法不再继续执行
    }
/**
     * 路径匹配，检查本次请求是否需要放行
     * @param requestURI
     * @return true-放行,false-拦截
     */

    public boolean check(String requestURI){
        boolean flag = false;
        for (String  url: passUrls) {
            //判断请求路径是否包含，放行路径
            if(PATH_MATCHER.match(url,requestURI)){
                flag = true;
                return flag;
            }
        }
        return flag;
    }
}

